import request from '@/utils/request'
import { AxiosRequestConfig } from 'axios'
import { Data } from './types/common'
import { UploadRawFile } from 'element-plus'

export const PC_API = '/pc-api'
export const APP_API = '/app-api'
export const ADMIN_API = '/admin-api'

export const httpRequest = <T>(data: AxiosRequestConfig) => {
  return request.request<any, Data<T>>(data)
}

// type Test = Exclude<articleType, { id: number }> //剔除id
// type Test1 = Omit<articleType, 'id' | 'title'> //剔除id,title
// type Test2 = Pick<articleType, 'id' | 'title'> //选择id,title

export function fileBase64(file: UploadRawFile): Promise<string> {
  return new Promise(function (resolve, reject) {
    const reader = new FileReader()
    let imgResult: string | ArrayBuffer | null
    reader.readAsDataURL(file)
    reader.onload = function () {
      imgResult = reader.result
    }
    reader.onerror = function (error) {
      reject(error)
    }
    reader.onloadend = function () {
      resolve(imgResult)
    }
  })
}

/**
 * 访问静态文件
 * @param url
 * @param fileName
 * @param params
 * @returns {Promise<AxiosResponse<any>>}
 * @constructor
 */
export function download(url: string, fileName?: string, params?: any) {
  return request
    .request({
      url: url,
      method: 'get',
      params: params || {},
      responseType: 'blob',
    })
    .then((content: any) => {
      const blob = new Blob([content.data || content], {
        type: 'application/octet-stream',
      })
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        const urlAry = url.split('/')
        const fileNameDefault = urlAry[urlAry.length - 1]
        elink.download = fileName || fileNameDefault
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    })
}
